package com.central.user.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class ServerUtil {

    private static String serverName = "root";

    private static String serverPassword = "BsdldSsh123456";

    private static Connection conn;

    private static String charset = Charset.defaultCharset().toString();

    public static String exeScriptClose(String ip) throws IOException {
        String exe = "cd /root;./close.sh";
        return exe(ip,exe);
    }

    public static String exeScriptStary(String ip) throws IOException {
        String exe = "cd /root;./startup.sh";
        return exe(ip,exe);
    }

    private static String exe(String ip, String exe) throws IOException {
        InputStream in = null;
        String result = "";
        if (login(ip)) {
            Session session = conn.openSession(); // 打开一个会话
            session.execCommand(exe);
            in = session.getStdout();
            result = processStdout(in, charset);
            session.close();
            conn.close();
        }
        return result;
    }

    private static String processStdout(InputStream in, String charset) throws IOException  {
        byte[] buf = new byte[1024];
        StringBuffer sb = new StringBuffer();
        while (in.read(buf) != -1) {
            sb.append(new String(buf, charset));
        }
        return sb.toString();
    }

    public static boolean login(String ip) throws IOException{
        conn = new Connection(ip);
        conn.connect();
        return conn.authenticateWithPassword(serverName,serverPassword);
    }
}
